package custom_components
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileReference;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	public class Export_to_Csv
	{
		private static  var saveString:String;
		public  function Export_to_Csv()
		{
		}
		
		public static function exportToCsv(data:ArrayCollection):void
		{
			var file:FileReference = new FileReference();
			var string:String = 'Name,Category,Address,Phone Number,Website,Email,Rating\n';
		
			
			for (var i : Number = 0 ; i < data.length ; i++)
			{
					var address :String = data[i].address;
					address = '"'+address+'"';
					var category :String = data[i].category;
					category = '"'+category+'"';
					string = string + 
						'"'+data[i].name+'",'+
						category+','+
						address+','+
						data[i].phone+',=HYPERLINK("'+data[i].website+'"),'+
						data[i].email+','+
						data[i].ratings;
					
					string = string + '\n';
					
			}
			saveString =  string;
			
			trace(string);
			file.save(string,'results.csv');
			file.addEventListener(IOErrorEvent.IO_ERROR , savefail);
			file.addEventListener(Event.COMPLETE , filesaved);
			/*var f:File = File.userDirectory;
			f.browseForSave('Save CSV');
			f.addEventListener(Event.SELECT , savehandler);
			f.addEventListener(IOErrorEvent.IO_ERROR , errorhandler);
			*/
		}
		
		protected static function errorhandler(event:IOErrorEvent):void
		{
			Alert.show('system does not allow to open file','Access Denied');
		}
		
		protected static function savehandler(event:Event):void
		{
			var savefile:File = File(event.target);
			var directory:String = savefile.url;  
			if(directory.indexOf(".csv") == -1)  
			{  
				directory += ".csv";  
			} 
			
			var file:File = new File();  
			file = file.resolvePath(directory);  
			var fileStream:FileStream = new FileStream();  
			fileStream.addEventListener(Event.CLOSE, onClose); 
			fileStream.addEventListener(IOErrorEvent.IO_ERROR, savefail);
			fileStream.openAsync(file, FileMode.WRITE);
			fileStream.writeUTFBytes(saveString);  
			fileStream.close();  
		}
		
		protected static function onClose(event:Event):void
		{
			Alert.show('File Successfully exported ' , 'Success');
			
		}
		
		protected static function filesaved(event:Event):void
		{
			Alert.show('File Successfully exported ' , 'Success');
		}
		
		protected static function savefail(event:IOErrorEvent):void
		{
			Alert.show('Close File if open And try again','Access Denied');
		}
		
	}
}